#coding:utf8
from collections import OrderedDict
from goods.models import GoodsChannel

def get_categories():
    # 初始化存储器
    categories = OrderedDict()
    # 获取一级分类
    channels = GoodsChannel.objects.order_by('group_id','sequence')

    #　对一级分类进行遍历
    for channel in channels:

        # 获取group_id
        group_id = channel.group_id

        # 判断group_id 是否在存储器，如果不在就初始化
        if group_id not in categories:

            categories[group_id] = {
                'channels':[],
                'sub_cats':[]
            }

        one = channel.category

        # 为channels 填充数据
        categories[group_id]['channels'].append({
            'id':one.id,
            'name':one.name,
            'url':channel.url
        })

        # 为　sub_cats 填充数据

        for two in one.goodscategory_set.all():
            # 初始化　容器
            two.sub_cats = []

            for three in two.goodscategory_set.all():
                two.sub_cats.append(three)

            # 组织数据
            categories[group_id]['sub_cats'].append(two)

    return categories
